<template>
    <Layout :left="left">
        <template #Menu>
            <Menu v-model:left="left" v-if="LoadState"></Menu>
        </template>
        <template #Tools>
            <Tools v-if="LoadState" />
        </template>
        <template #Content>
            <BoardVue v-if="LoadState" />
        </template>
        <template #Active>
            <ActiveBoard v-if="LoadState" />
        </template>
        <template #Options>
            <Options v-if="LoadState" />
        </template>
    </Layout>
</template>

<script setup>
import Layout from '../View/_Layout.vue'
import { inject, nextTick, onUnmounted, provide, ref, watch } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import Menu from './Menu.vue'
import DocumentEditor from '../Event/Document.ts'
import BoardVue from './Board.vue'
import ActiveBoard from './ActiveBoard.vue'
import Tools from './Tools.vue'
import Options from './Options.vue'


const left = ref(48);

const _Event = new DocumentEditor();
provide('StateEvent', _Event);

onBeforeRouteLeave(() => {
    const answer = window.confirm('您确定您要离开页面么? 离开后您将失去您尚未保存的操作!');
    if (!answer) return false;
})

watch(() => _Event.CacheData.value, () => {
    nextTick(() => {
        _Event.RefreshActiveBoard();
    })
}, { deep: true })

 
const LoadState = ref(false);

const AppOnEvent = inject('AppOnEvent');
const AppOffEvent = inject('AppOffEvent');

let DataCache = null;

const CellLoadEnd = function () {
    LoadState.value = true;
    if (DataCache) {
        _Event.SetData(DataCache);
    }
}
AppOnEvent('VisualEditor-Core.CellLoadEnd', CellLoadEnd)

defineExpose({
    SetData(Data) {
        if (LoadState.value) {
            _Event.SetData(Data)
        } else {
            DataCache = Data;
        }
    },
    Save() { _Event.Save() },
    Preview() { _Event.Preview() },
    Log() {
        console.log(JSON.stringify(_Event.CacheData.value.Rules, '', '  '));
    }
})

onUnmounted(() => {
    _Event.destroy();
    AppOffEvent('VisualEditor-Core.CellLoadEnd', CellLoadEnd)
})

</script>

<style lang="less" scoped>
.Board {
    width: 100%;
    height: 99.5%;
}
</style>